package com.listen.controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.listen.common.HttpClientUtil;
/**
 * 八大员培训
 * @author Administrator
 *
 */
public class Badayuan extends HttpServlet{
	private static final long serialVersionUID = 1L;
	private static String urlprefix = "";
	private static String loginurl="";
	private static String __viewstate="";
	private static String __viewstategenerator="C2EE9ABB";
	private static String __eventvalidation="";
	private String txtUserName = null;
	private String txtPwd = null;
	private String ZY;
	private String cookie ;
	private String userid;
	private int numBegin;
	private int numEnd;
	List<String> msgList = null;
	private String info;
	
	private RequestConfig requestConfig = RequestConfig.custom()  
            .setSocketTimeout(15000)  
            .setConnectTimeout(15000)  
            .setConnectionRequestTimeout(15000)  
            .build();
	
	public static void main(String[] args) {
		Badayuan jxy = new Badayuan();
		//jxy.login();
		/*jxy.txtUserName="362204198002131087";
		jxy.txtPwd="888888";
		jxy.numBegin=1;
		jxy.numEnd=5;
		jxy.ZY="8";*/
		jxy.getHtml();
		
	}
	
	//接收页面POST请求
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
	   throws ServletException, IOException {
		msgList = new LinkedList<String>();
		this.ZY = req.getParameter("ZY");
		this.txtUserName = req.getParameter("txtUserName");
		this.txtPwd = req.getParameter("txtPwd");
		this.numBegin = Integer.parseInt(req.getParameter("numBegin"));
		this.numEnd= Integer.parseInt(req.getParameter("numEnd"));
		System.out.println("txtUserName="+txtUserName);
		this.getHtml();
		req.setAttribute("msgList", msgList);
		req.setAttribute("page", 1);
		req.getRequestDispatcher("/result.jsp").forward(req, resp);
	}
	
	//接收页面get请求
	 @Override
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
	   throws ServletException, IOException {
		 return;
	 }
	
	//智能登录第一步：解析八大员综合登录页面，根据用户选择的专业智能进入对应专业的登录页面
	public void getHtml(){
		try {
            if(this.ZY==null||"".equals(ZY.trim())){
            	print("未获取到八大员相关职业信息--->ZY="+this.ZY);
            }else{
            	Document doc = Jsoup.connect("http://urdt.cn/Badayuan/badyuan.html").get();
            	Elements links = doc.getElementsByTag("a");
            	for (Element link: links) {
                    String linkHref = link.attr("href");
                    String lastChar = linkHref.substring(linkHref.length()-1);
                    if(lastChar.equals(this.ZY)){
                    	urlprefix = linkHref.substring(0,linkHref.lastIndexOf("/"));
                    	loginurl = linkHref;
                    	toLoginPage(loginurl);
                    	break;
                    }
                }
            }
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	//智能听课第二部：跳转到具体专业登录页面，并从页面抓取登录所需相关参数
	private void toLoginPage(String httpUrl){
		CloseableHttpResponse response = null;
		CloseableHttpClient httpClient = null;
		try {
			HttpGet httpGet = new HttpGet(httpUrl);
			httpClient = HttpClients.createDefault();  
	        httpGet.setConfig(requestConfig);
	        response = httpClient.execute(httpGet);
			int state = response.getStatusLine().getStatusCode();
			if(state == 200){
				HttpEntity entity = response.getEntity();  
				String html = EntityUtils.toString(entity);
			    Document document = Jsoup.parse(html);
			    Element parm1 = document.getElementById("__VIEWSTATEGENERATOR");
			    __viewstategenerator = parm1.attr("value");
			    Element parm2 = document.getElementById("__EVENTVALIDATION");
			    __eventvalidation = parm2.attr("value");
			    Element parm3 = document.getElementById("__VIEWSTATE");
			    __viewstate = parm3.attr("value");
			    this.login();
			}else{
				print("自动获取登录页面参数失败!");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally { 
            try {  
                // 关闭连接,释放资源  
                if(response != null){  
                    response.close();  
                } 
                if(httpClient != null){
                    httpClient.close();  
                }
            } catch (IOException e) {  
                e.printStackTrace();  
            }  
        }
	}
	 
	//智能听课第三步：智能登录
	public void login(){
		Map<String, String> maps = new HashMap<String, String>();
        maps.put("__VIEWSTATE", __viewstate); 
        maps.put("__VIEWSTATEGENERATOR", __viewstategenerator);
        maps.put("__EVENTVALIDATION",__eventvalidation); 
        maps.put("txtUserName",txtUserName);
        maps.put("txtPwd",txtPwd);
        maps.put("ddlType", "2"); 
        maps.put("btnLogin", "");
        maps.put("txtLoginName", ""); 
        maps.put("txtDM", "");
        maps.put("txtFR", ""); 
        maps.put("zhjg", "");
        maps.put("zhfr", "");
        CloseableHttpResponse response = null;
        try {
        	System.out.println(loginurl);
        	HttpPost httpPost = new HttpPost(loginurl);// 创建httpPost
        	httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
        	httpPost.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
        	response = HttpClientUtil.getInstance().sendHttpPost(maps,httpPost);
        	int state = response.getStatusLine().getStatusCode();
        	if(state == 302){
        		//String url = response.getLastHeader("Location").getValue();
        		Header[] hearders = response.getHeaders("Set-Cookie");
        		String sessionId = hearders[0].getValue();
        		this.cookie = sessionId.substring(0, sessionId.indexOf(";") + 1);
        		String userIdCookie = hearders[1].getValue();
        		this.userid = userIdCookie.substring(0, userIdCookie.indexOf(";") + 1);
        		String infoCookies = hearders[2].getValue();
        		this.info = infoCookies.substring(0, infoCookies.indexOf(";"));
        		updateStudyVideo();
        	}else{
        		print("登录失败！！！当前账户-"+txtUserName+"-所选职业为:"+this.getZy(ZY)+",请检查职业是否匹配!");
        	}
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			if(response!=null){
				try {
					response.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	//智能听课第四步：登录成功后跳转
	/*private void sendRedirect(String httpUrl){
		HttpGet httpGet = null;
		CloseableHttpResponse response = null;
		try {
			httpGet = new HttpGet(httpUrl);
			response = HttpClientUtil.getInstance().sendHttpGet(httpGet);
			int state = response.getStatusLine().getStatusCode();
			if(state == 200){
				updateStudyVideo();
			}else{
				print("登录跳转失败!");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}*/
	
	//智能听课第五步：更新课件状态为已听
	public void updateStudyVideo(){
		CloseableHttpResponse response = null;
		for (int i = numBegin; i <= numEnd; i++) {
			try {
				String rvCode = i < 10 ? "0000" + i : "000" + i;
				String rvCodeJson = "{\"RVCode\":\"" + rvCode + "\"}";
				String cookie = this.cookie + this.userid + " RID=" + rvCode + "; totaltime=2281; checkUid=38060; nowtime=2281";
				HttpPost httpPost = new HttpPost(urlprefix+"/StudentClass4/WatchVideo4.aspx/UpdateStudyType");// 创建httpPost
				httpPost.setHeader("X-Requested-With","XMLHttpRequest");
				httpPost.setHeader("Content-Type","application/json; charset=UTF-8");
				httpPost.setHeader("Accept","application/json");
				httpPost.setHeader("Cookie", cookie);
				response = HttpClientUtil.getInstance().sendHttpPost(httpPost, rvCodeJson);
				int state = response.getStatusLine().getStatusCode();
				if(state == 200){
					print("账号-"+txtUserName +" 第"+i +"个视频已播完");
				}else{
					print("账号-"+txtUserName +" 第"+i +"视频播放失败!");
					break;
				}
				Thread.sleep(5000);
			} catch (Exception e) {
				e.printStackTrace();
			}finally{
				if(response!=null){
					try {
						response.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		}
		logout();
	}
	
	//智能听课第六步：退出登录
	public void logout(){
		HttpGet httpGet = null;
		CloseableHttpResponse response = null;
		try {
			String path = urlprefix+"/Public/Logout.aspx?id="+ZY;
			httpGet = new HttpGet(path);
			String cookie = this.cookie + this.userid + this.info +"totaltime=2281; checkUid=38060; nowtime=2281";
			httpGet.setHeader("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
			httpGet.setHeader("Cookie", cookie);
			response = HttpClientUtil.getInstance().sendHttpGet(httpGet);
			int state = response.getStatusLine().getStatusCode();
			System.out.println("logout state="+state);
			if(state == 200 || state == 302){
				print("退出登录成功!");
			}else{
				print("退出登录失败!");
			}
		} catch (Exception e) {
			print("退出登录异常--->"+e);
			e.printStackTrace();
		}
	}
	
	public void print(String msg){
		msgList.add(msg);
		System.out.println(msg);
	}
	
	//获取八大员对应专业
	public String getZy(String zy){
		switch(zy){
		case "1":{
			return "施工员";
		}
		case "2":{
			return "标准员";
		}
		case "3":{
		return "材料员";
		}
		case "4":{
			return "机械员";
		}
		case "5":{
			return "安全员";
		}
		case "6":{
			return "资料员";
		}
		case "7":{
			return "质量员";
		}
		case "8":{
			return "劳务员";
		}
		default:{
			return null;
		}
		}
	}
}
